﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using CustomerEmailer.Common;
using System.Net.Mail;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;

namespace CustomerEmailer
{
    static class Program
    {
        static Main main;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            main = new Main();
            Application.Run(main);
        }
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException((Exception)e.ExceptionObject);
        }

        static void HandleException(Exception e)
        {
            try
            {
                if (Utils.updatingContacts)
                {
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?cancelContactsAvailable");
                    request.Method = "GET";
                    request.ContentType = "text/plain";
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                }
                if (Utils.updatingHistory)
                {
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?cancelHistoryAvailable");
                    request.Method = "GET";
                    request.ContentType = "text/plain";
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                }
            }
            catch (Exception ex) { }
            Logger x = new Logger();
            main.SyncTimer.Enabled = false;
            main.SyncTimer.Stop();
            string errorString = e.Message + '\n' + e.StackTrace;
            
            x.Log(Utils.GetSetting("ErrorFile"), errorString);
            EmailService emailService = new EmailService((EmailService.EmailServiceName)int.Parse(Utils.GetSetting("ServiceName")),
                Utils.GetSetting("Email"), Utils.GetSetting("Password"));
            MailMessage message = new MailMessage(new MailAddress(Utils.GetSetting("Email"), Utils.GetSetting("UserName")), new MailAddress("microdev@gmail.com"));
            message.Body = errorString;
            message.IsBodyHtml = false;
            message.CC.Add("l.yadid@gmail.com"); 
            using (Bitmap bitmap = new Bitmap(main.Size.Width, main.Size.Height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.CopyFromScreen(new Point(main.DesktopLocation.X, main.DesktopLocation.Y), new Point(0, 0), main.Size);
                }

                bitmap.Save(@".\ApplicationData\error.jpg", ImageFormat.Jpeg);
            }
            message.Subject = "שגיאת תכנה במקסימייל" +" Ver" +Application.ProductVersion;
            message.Attachments.Add(new Attachment(Utils.GetXmlFileLocation("error.jpg")));
            message.Attachments.Add(new Attachment(Utils.GetXmlFileLocation("customers.xml")));
            message.Attachments.Add(new Attachment(Utils.GetXmlFileLocation("settings.xml")));
            message.Attachments.Add(new Attachment(Utils.GetMainFolderLocation("History.db")));
            emailService.sendMessage(message);
            MessageBox.Show("אירעה שגיאה קריטית בתכנה. השגיאה נשלחה למפתחים ותתוקן בהקדם. \n התכנה כעת תצא.");
            Application.Exit();
        }
    }
}
